// var powerlist = ["/micro/ident-group:queryList","/micro/ident-group:add"];
<!--自定义函数判断权限-->
var userInfo = getAuthority();
var powerlist = JSON.parse(userInfo).permissions;
/*自定义函数判断权限*/
template.defaults.imports.hasPower = function(data){
    if(powerlist.includes(data)){
        return true;
    }
    return false;
};

layui.use(['layer', 'form', 'table', 'util', 'dtree','laypage'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var util = layui.util;
    var admin = layui.admin;
    var dtree = layui.dtree;
    var laypage = layui.laypage;

    var Authorization;//请求接口用
    var count = 0;//总个数
    var current=1;//当前页
    var this_parid;//用于存储选中后的分组
    var fistRenderPage= true;//是否第一次渲染分组分页
    var firstRenderValuePage = true;//是否第一次渲染单位值分页
    var unitsValue;
    //获取权限方法
    if(userInfo){
        var access_token = localStorage.getExpire("access_token");
        var token_type = localStorage.getExpire("token_type");
        Authorization = token_type+" "+access_token;
        getUnits();
        getUnitsList();
        getUnitGroupPower();
        getUnitValuePower();

    }


    // 添加
    $('#addUnitGroup').click(function () {
        showAddUnitGroup();
    });
    $('#addUnitValue').click(function () {
        showAddUnitValueModel();
    })

    // 单位分组工具条点击事件
    table.on('tool(unitGroup)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'editGroup') { // 修改
            showEditUnitGroup(data);
        } else if (layEvent === 'delGroup') { // 删除
            doDelGroup(obj);
        }
    });
    //监听行单击事件
    table.on('row(unitGroup)', function(obj){
        getIdenValueData(obj.data.id)
        obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
    });
    // 单位值工具条点击事件
    table.on('tool(unitValue)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'editValue') { // 修改
            showEditUnitValue(data);
        } else if (layEvent === 'delValue') { // 删除
            showDeleteUnitValue(obj);
        }else if(layEvent==='moveMenu'){//移动目录
            firstRenderValuePage = true;
            getGroupList(data);
        }
    });
    //控制单位分组权限
    function getUnitGroupPower() {
        var str = template("unitGroup-tmpl",{});
        document.getElementById("unitGroup-tmpl-box").innerHTML = str;

        var str = template("unitGroup-table-tmpl",{});
        document.getElementById("unitGroup-table-tmpl-box").innerHTML = str;
    }
    //控制单位值权限
    function getUnitValuePower() {
        var str = template("unitValue-tmpl",{});
        document.getElementById("unitValue-tmpl-box").innerHTML = str;

        var str = template("unitValue-table-tmpl",{});
        document.getElementById("unitValue-table-tmpl-box").innerHTML = str;
    }
    //获取单位分组列表信息
    function getUnitsList() {
        var req={
            current: current,
            size: pageSize
        };
        axios.get(metadataUrl.unitsGroup.allUnitsGroup.unitsGroupList,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    renderIdenGroupTable(data);
                    getIdenValueData(data.records[0].id)
                }
            })
            .catch(function (error) {
                console.log(error);
            });
    }
    //渲染单位分组表格
    function renderIdenGroupTable(unitsData) {
        table.render({
            elem: '#unitGroup',
            size: 'sm', //小尺寸的表格
            data: unitsData.records,
            cols: [[
                {type: 'numbers', title: '#'},
                {field: 'cnname', align: 'center', title: '名称'},
                {field: 'memo', align: 'center', title: '描述'},
                {align: 'center', toolbar: '#unitGroup-table-tmpl-box', title: '操作', minWidth: 120}
            ]]
        });
        var divbox = $("#unitGroup").next(".layui-table-view");
        $(divbox).find("table tr").eq(1).click();
        //第一次才渲染分页
        if(fistRenderPage){
            laypage.render({
                elem: 'idenGroupPageBox'
                ,count: unitsData.total,
                limit:unitsData.size,
                groups:1,
                current:unitsData.current
                ,layout: ['count','prev','page', 'next']
                ,jump: function(obj, first){
                    if(!first){
                        current = obj.curr;
                        fistRenderPage = false;
                        getUnitsList();
                    }
                }
            });
        }

    }
    //获取单位值列表
    function getIdenValueData(id) {
        var valueReq={
            current: current,
            size: pageSize,
            parid:id
        }
        this_parid = id
        axios.get(metadataUrl.unitsGroup.idenData.idenDataList,{
            params: valueReq,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    renderIdenValueTable(data)
                }
            })
            .catch(function (error) {
                console.log(error);
            });
    }
    //渲染单位值表格
    function renderIdenValueTable(idenValue) {
        table.render({
            elem: '#unitValue',
            size: 'sm', //小尺寸的表格
            data: idenValue.records,
            cols: [[
                {type: 'numbers', title: '#'},
                {field: 'cnname', title: '中文名'},
                {field: 'enname', align: 'center', title: '英文名'},
                {field: 'valueType', align: 'center', title: '值类型',templet:function (d) {
                        for(let i = 0;i<unitsValue.length;i++){
                            if(d.valueType == unitsValue[i].value){
                                return unitsValue[i].key
                            }
                        }
                    }},
                {field: 'memo', align: 'center', title: '值描述'},
                {align: 'center', toolbar: '#unitValue-table-tmpl-box', title: '操作', minWidth: 200}
            ]]
        });
        //第一次才渲染分页
        if(firstRenderValuePage){
            laypage.render({
                elem: 'idenValuePageBox'
                ,count: idenValue.total,
                limit:idenValue.size,
                groups:1,
                current:idenValue.current
                ,layout: ['count','prev','page', 'next']
                ,jump: function(obj, first){
                    if(!first){
                        current = obj.curr;
                        firstRenderValuePage = false;
                        getIdenValueData(this_parid);
                    }
                }
            });
        }
    }
    // 删除
    function doDelGroup(obj) {
        layer.confirm('确定要删除“' + obj.data.cnname + '”吗？', {
            skin: 'layui-layer-admin',
            shade: .1
        }, function (i) {
            layer.close(i);
            layer.load(2);
            axios({
                method: 'delete',
                url:metadataUrl.unitsGroup.allUnitsGroup.deleteUnitsGroup + obj.data.id,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        layer.closeAll('loading');
                        layer.msg("成功删除", {icon: 1});
                        fistRenderPage = true
                        getUnitsList();
                    } else {
                        layer.msg(res.data.message, {icon: 2});
                        layer.closeAll('loading');
                    }
                })
                .catch(function (err) {
                    console.log(err);
                })
        });
    }
    // 显示编辑单位分组弹窗
    function showEditUnitGroup(mRole) {
        admin.open({
            type: 1,
            title: '编辑单位分组',
            area: ['350px', '350px'],
            offset:'auto',
            content: $('#editUnitGroupModel').html(),
            success: function (layero, dIndex) {
                // 表单提交事件
                form.val('modelUserForm', mRole);  // 回显数据
                form.on('submit(modelSubmitUser)', function (data) {
                    layer.load(2);
                    let formData = mRole;
                    formData.cnname = data.field.cnname;
                    formData.memo = data.field.memo;
                    axios({
                        method: 'put',
                        data:formData,
                        url:metadataUrl.unitsGroup.allUnitsGroup.editUnitsGroup,
                        headers:{
                            'Authorization':Authorization
                        }
                    })
                        .then(function (res) {
                            if (res.status == 200&&res.data.message=="success") {
                                getUnitsList();
                                layer.closeAll('loading');
                                layer.close(dIndex);
                                layer.msg("编辑成功", {icon: 1});
                            } else {
                                layer.msg(res.data.message, {icon: 2});
                                layer.closeAll('loading');
                            }
                        })
                        .catch(function (err) {
                            console.log(err);
                        })
                    return false;
                });
            }
        });
    }
    //显示新增单位分组弹窗
    function showAddUnitGroup() {
        admin.open({
            type: 1,
            title: '新增单位分组',
            area: ['350px', '350px'],
            offset:'auto',
            content: $('#addUnitGroupModel').html(),
            success: function (layero, dIndex) {
                // 表单提交事件
                form.on('submit(modelSubmitUser)', function (data) {
                    layer.load(2);
                    let formData = data.field;
                    axios({
                        method: 'post',
                        data:formData,
                        url:metadataUrl.unitsGroup.allUnitsGroup.addUnitsGroup,
                        headers:{
                            'Authorization':Authorization
                        }
                    })
                        .then(function (res) {
                            if (res.status == 200&&res.data.message=="success") {
                                fistRenderPage = true
                                getUnitsList();
                                layer.closeAll('loading');
                                layer.close(dIndex);
                                layer.msg("新增成功", {icon: 1});
                            } else {
                                layer.msg(res.data.message, {icon: 2});
                                layer.closeAll('loading');
                            }
                        })
                        .catch(function (err) {
                            console.log(err);
                        })
                    return false;
                });
            }
        });
    }
    //显示新增单位值弹窗
    function showAddUnitValueModel() {
        admin.open({
            type: 1,
            title: '新增单位值',
            area: ['350px', '500px'],
            offset:'auto',
            content: $('#addUnitValueModel').html(),
            success: function (layero, dIndex) {
                var str = template("template-unitsValue-index-tmpl",{unitsValue});
                document.getElementById("unitValueType").innerHTML = str;
                form.render('select'); //刷新select选择框渲染
                // 表单提交事件
                form.on('submit(modleAddValue)', function (data) {
                    data.field.parid = this_parid;
                    layer.load(2);
                    let formData = data.field;
                    axios({
                        method: 'post',
                        data:formData,
                        url:metadataUrl.unitsGroup.idenData.addIdenData,
                        headers:{
                            'Authorization':Authorization
                        }
                    })
                        .then(function (res) {
                            if (res.status == 200&&res.data.message=="success") {
                                firstRenderValuePage = true
                                getIdenValueData(this_parid)
                                layer.closeAll('loading');
                                layer.close(dIndex);
                                layer.msg("新增成功", {icon: 1});
                            } else {
                                layer.msg(res.data.message, {icon: 2});
                                layer.closeAll('loading');
                            }
                        })
                        .catch(function (err) {
                            console.log(err);
                        })
                    return false;
                });
            }
        });
    }
    //显示修改单位值弹窗
    function showEditUnitValue(mRole) {
        console.log(mRole)
        admin.open({
            type: 1,
            title: '编辑单位值',
            area: ['350px', '500px'],
            offset:'auto',
            content: $('#editUnitValueModel').html(),
            success: function (layero, dIndex) {
                var str = template("template-unitsValue-index-tmpl",{unitsValue});
                document.getElementById("unitEditType").innerHTML = str;
                form.render('select'); //刷新select选择框渲染
                form.render('checkbox'); //刷新select选择框渲染
                form.val('modelUserForm', mRole);  // 回显数据
                form.on('switch(autoplay)', function(data){
                    mRole.status = data.elem.checked?1:0;
                });
                // 表单提交事件
                form.on('submit(edit-Iden)', function (data) {
                    layer.load(2);
                    let formData = mRole;
                    formData.cnname = data.field.cnname;
                    formData.memo = data.field.memo;
                    axios({
                        method: 'put',
                        data:formData,
                        url:metadataUrl.unitsGroup.idenData.editIdenData,
                        headers:{
                            'Authorization':Authorization
                        }
                    })
                        .then(function (res) {
                            if (res.status == 200&&res.data.message=="success") {
                                getIdenValueData(this_parid)
                                layer.closeAll('loading');
                                layer.close(dIndex);
                                layer.msg("编辑成功", {icon: 1});
                            } else {
                                layer.msg(res.data.message, {icon: 2});
                                layer.closeAll('loading');
                            }
                        })
                        .catch(function (err) {
                            console.log(err);
                        })
                    return false;
                });
            }
        });
    }
    //点击移动分组的时候加载分组列表
    function getGroupList(idenData) {
        axios.get(metadataUrl.unitsGroup.allUnitsGroup.unitsGroupList+"?current="+current+"&"+"size"+"=8",{
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    showMoveMenuModel(data.records,idenData)
                }
            })
            .catch(function (error) {
                console.log(error);
            });
    }
    //显示移动目录弹窗
    function showMoveMenuModel(obj,idenData) {
        var arr = obj;
        for(var i in arr){
            if(arr[i].id == idenData.parid){
                arr.splice(i,1);
            }
        }
        admin.open({
            type: 1,
            title: '移动所属单位分组',
            area: ['500px', '500px'],
            offset:'auto',
            content: $('#moveMenuModel').html(),
            success: function (layero, dIndex) {
                table.render({// 渲染表格
                    elem: '#moveMenuTable',
                    size: 'sm', //小尺寸的表格
                    skin:'nob',
                    data:arr,
                    cols: [[
                        {type:'numbers', title: '#'},
                        {field: 'cnname', align: 'center', title: '名称'},
                        {field: 'memo', align: 'center', title: '描述'}
                    ]]
                });
                let chooseGroup;//选中分组暂存
                //监听行单击事件（单击事件为：rowDouble）
                table.on('row(moveMenuTable)', function(move_obj){
                    chooseGroup = move_obj.data;
                    //标注选中样式
                    move_obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
                });
                // 表单提交事件
                form.on('submit(move-group)', function () {
                    layer.load(2);
                    let formData = idenData;
                    if(chooseGroup){
                        formData.parid = chooseGroup.id;
                        axios({
                            method: 'put',
                            data:formData,
                            url:metadataUrl.unitsGroup.idenData.editIdenData,
                            headers:{
                                'Authorization':Authorization
                            }
                        })
                            .then(function (res) {
                                if (res.status == 200&&res.data.message=="success") {
                                    getIdenValueData(this_parid)
                                    layer.closeAll('loading');
                                    layer.close(dIndex);
                                    layer.msg("操作成功", {icon: 1});
                                } else {
                                    layer.msg(res.data.message, {icon: 2});
                                    layer.closeAll('loading');
                                }
                            })
                            .catch(function (err) {
                                console.log(err);
                            })
                    }else{
                        layer.msg("还没有选择所要移动的分组", {icon: 2});
                        layer.closeAll('loading');
                    }

                    return false;
                });
            }
        });

    }

    // 删除单位值
    function showDeleteUnitValue(obj) {
        layer.confirm('确定要删除 “' + obj.data.cnname + '”', {
            skin: 'layui-layer-admin',
            shade: .1
        }, function (i) {
            layer.close(i);
            layer.load(2);
            axios({
                method: 'delete',
                url:metadataUrl.unitsGroup.idenData.deleteIdenData + obj.data.id,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        firstRenderValuePage = true
                        layer.closeAll('loading');
                        layer.msg("成功删除", {icon: 1});
                        getIdenValueData(this_parid)
                    } else {
                        layer.msg(res.data.message, {icon: 2});
                        layer.closeAll('loading');
                    }
                })
                .catch(function (err) {
                    console.log(err);
                })
        });
    }
    //获取单位值
    function getUnits() {
        axios.get(metadataUrl.unitsGroup.idenData.getUnitsType,{
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    unitsValue = data
                }
            })
            .catch(function (error) {
                console.log(error);
            });
    }
});
